package chapter4;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by uu on 2017/6/19.
 */
public class alert_customer {
        private static final String AMQP_EXCHANGES="alerts";
        private static boolean autoAck = true; // 是否默认Ack
    public static void main(String[] args) throws Exception{
        ConnectionFactory factory =  new ConnectionFactory();
                /*factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost");*/
        factory.setUsername("alert_user");
        factory.setPassword("alertme");
        factory.setVirtualHost("/");
        factory.setHost("localhost");
        factory.setPort(5672);
        Connection conn = factory.newConnection();
        final Channel channel = conn.createChannel();

        channel.exchangeDeclare(AMQP_EXCHANGES,"topic",true);
        //critical队列和critical.*绑定
        channel.queueDeclare("critical",true,false,false,null);
        channel.queueBind("critical",AMQP_EXCHANGES,"critical.*");
        //rate_limit队列和*.rate_limit绑定
        channel.queueDeclare("rate_limit",true,false,false,null);
        channel.queueBind("rate_limit",AMQP_EXCHANGES,"*.rate_limit");

        channel.basicConsume("critical",autoAck,"critical",
                new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                        String routingKey = envelope.getRoutingKey();
                        String contentType = properties.getContentType();
                        long deliveryTag = envelope.getDeliveryTag();
                        // (process the message components here ...)
                        System.out.println(new String(body,"UTF-8"));
                        channel.basicAck(deliveryTag, false);
                    }
                });

        channel.basicConsume("rate_limit",autoAck,"rate_limit",
                new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(String consumerTag,
                                               Envelope envelope,
                                               AMQP.BasicProperties properties,
                                               byte[] body)
                            throws IOException
                    {
                        String routingKey = envelope.getRoutingKey();
                        String contentType = properties.getContentType();
                        long deliveryTag = envelope.getDeliveryTag();
                        // (process the message components here ...)
                        System.out.println(new String(body,"UTF-8"));
                        channel.basicAck(deliveryTag, false);
                    }
                });
        System.out.println("Ready for alerts!");
    }

}
